<script setup>
import { ref, onMounted,watch } from 'vue'
import { registerMap } from 'echarts'
import worldCh from '@/assets/json/worldCh.json'
import { useWorldMap } from '@/hooks/chart/useWorldMap'
const { options } = useWorldMap()
const emit = defineEmits(['addCountry'])
const props = defineProps({
  MapList: {
    type: Array,
    required: true,
    default: ()=>[]
  }
})
const currentcountry=ref(null)
const chartRef = ref()
const init = () => {
  registerMap('world', worldCh)
  chartRef.value.loadingChart(true)
  chartRef.value.initChart()
  chartRef.value.clickChart(mapClick)
  getInfo(true)
}
// 图例最大值
const legendMax=(data)=>{
  const valueArray = data.map(obj => obj.value);
  // 找到value数组中的最大值作为图例上限(10为计量单位)
  const maxValue = Math.ceil(Math.max(...valueArray)/10)*10;
  return maxValue
}
// 地图数据请求
const getInfo = (flag) => {
  options.series[0].data=MapList()
  options.visualMap.max = legendMax(options.series[0].data) //将数据最大值作为图例上限
  options.visualMap.show = false //隐藏图例
  flag ? chartRef.value.updateChart() : chartRef.value.initChart()
}
const mapClick=(e)=>{
  if(!e.value){return}
  currentcountry.value=e.name
  emit('addCountry', currentcountry.value)
}
// 地图数据列表处理
const MapList=()=>{
  const MapUpdata=props.MapList.map(item=>{
  const _item={
      name: '',
      value: 0
    }
    _item.name=item.key
    _item.value=item.value
    return _item
  })
  return MapUpdata
}
// 监听更新
watch(()=>props.MapList,()=>{
  getInfo(true)
})
onMounted(() => {
  init()
})
</script>
<template>
  <div>
    <jmp-chart ref="chartRef" v-model:option="options"></jmp-chart>
  </div>
</template>
<style lang="scss" scoped></style>
